package com.educate.service.impl;

import com.educate.common.dto.VideoFileDto;
import com.educate.common.lang.Const;
import com.educate.dao.VideoDao;
import com.educate.pojo.Video;
import com.educate.service.VideoService;
import com.educate.util.OssFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yjj
 * @date 2021/12/23
 * @Description
 */
@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoDao videoDao;

    @Autowired
    private OssFileUpload ossFileUpload;

    /**
     * 根据课程ID获取所有的视频
     * @param courseId
     * @return
     */
    @Override
    public List<VideoFileDto> getAllVideosByCourseId(String courseId) {
        //根据课程ID查询对应的所有视频
        List<Video> videoList = videoDao.selectAllVideosByCourseId(courseId);
        //定义结果集合
        List<VideoFileDto> resList = new ArrayList<>();
        //依次遍历每个视频实体，再按要求返回自定义的结果实体(VideoFileDto)
        for (Video video : videoList) {
            VideoFileDto videoFileDto = new VideoFileDto();
            videoFileDto.setId(video.getId());
            //组合视频访问url
            String[] temp = video.getFileName().split("/");
            videoFileDto.setName(temp[temp.length-1]);
            videoFileDto.setUrl(Const.OSS_BASE_URL + video.getFileName());
            videoFileDto.setPlayTime(video.getPlayTime());
            resList.add(videoFileDto);
        }
        return resList;
    }


    /**
     * 删除课程视频
     * @param courseId
     * @param videoId
     */
    @Override
    @Transactional
    public void deleteVideo(String courseId, String videoId) {
        String fileName = videoDao.getVideoFileNameByVideoId(videoId);
        videoDao.deleteVideoByVideoId(videoId);
        videoDao.deleteVideoLinkCourseByIdS(videoId,courseId);
        if(fileName != null){
            ossFileUpload.ossDelete(fileName);
        }
    }
}
